import { EnumErrorCode } from "../../../../../common/enum/EnumErrorCode";
import { CS_Login, SC_Login } from "../../../../../common/protocols/Proto_Login";
import { CS_Register, SC_Register } from "../../../../../common/protocols/Proto_Register";
import { Behavior } from "../behavior/Behavior";
import { EnumBehaviorActionType } from "../behavior/EnumBehaviorActionType";
import { EnumBehaviorReturn } from "../behavior/EnumBehaviorReturn";
import { RobotEntity } from "../RobotEntity";
import { EnumBehaviorType } from "./EnumBehaviorType";

export class BehaviorLogin extends Behavior {

    public type: EnumBehaviorType = EnumBehaviorType.Login;

    public actionType: EnumBehaviorActionType = EnumBehaviorActionType.Sequence;

    public actionState: EnumBehaviorReturn = EnumBehaviorReturn.IDLE
    constructor() {
        super();

    }

    public condition(): boolean {
        const entity: RobotEntity = this.getEntity();
        
        return !entity._data && (this.actionState != EnumBehaviorReturn.RUNNING );

    }


    public action(): EnumBehaviorReturn {

        this.login();
        return this.actionState;
    }


    private login(): void {
        const entity: RobotEntity = this.getEntity();
        const cs: CS_Login = new CS_Login();
        cs.username = this.entity.username;
        cs.password = this.entity.password;

        this.actionState = EnumBehaviorReturn.RUNNING;

        entity.sendMsg(cs, (sc: SC_Login) => {
            if (sc.errorcode === EnumErrorCode.OK) {
                entity.setData(sc.gamedata,sc.userid);
                this.actionState = EnumBehaviorReturn.SUCCESS;
            }
            else if (sc.errorcode === EnumErrorCode.Account_notFound) {
                this.register();
            }
            else {

            }
        });


    }

    private register(): void {

        const cs: CS_Register = new CS_Register();
        cs.username = this.entity.username;
        cs.password = this.entity.password;
        this.entity.sendMsg(cs, (sc: SC_Register) => {
            if (sc.errorcode === EnumErrorCode.OK) {
                this.login();
            }
        });
    }
}